const file = function () { }
file.prototype = {
    dl(key, url = null, resolve = function () { }, reject = function () { }) {
        const that = this;
        url = url ? url : 'cloud://cards-2c53b0.6361-cards-2c53b0-1258076431/mold/' + key + '.png';
        wx.cloud.downloadFile({
            fileID: url,
            filePath: wx.env.USER_DATA_PATH+"/"+key+(key=="font"?".ttf":".png"),
            success(res) {
                if (res.statusCode === 200) {
                    const fs = wx.getFileSystemManager();
                    fs.saveFile({
                        tempFilePath: res.tempFilePath,
                        success(res) {
                            console.log(key+"下载成功")
                            wx.setStorageSync(key, res.savedFilePath);
                            resolve(res.savedFilePath);
                        },
                        fail() {
                            console.log(key +"保存失败")
                            that.clean();
                            reject();
                        }
                    })
                }
                else {
                    console.log(key +"保存失败")
                    that.clean();
                    reject();
                }
            },
            fail() {
                console.log(key +"保存失败")
                that.clean();
                reject();
            }
        })
    },
    get keys() {
        return ['nmonster', 'ymonster', 'rmonster', 'tmonster', 'cmonster', 'link', 'l_emonster', 'l_nmonster', 'l_ymonster', 'l_rmonster', 'l_tmonster', 'font'];
    },
    check(key) {
        return wx.getStorageSync(key);
    },
    get miss() {
        let res = [];
        this.keys.forEach((key, i, keys) => {
            if (!this.check(key)) {
                res.push(key);
            }
        })
        return res;
    },
    get own() {
        let res = [];
        this.keys.forEach((key, i, keys) => {
            if (this.check(key)) {
                res.push(key);
            }
        })
        return res;
    },
    fill(callback = function () { }) {
        console.log("丢失值为：",this.miss);
        wx.showNavigationBarLoading();
        const miss=this.miss;
        miss.forEach((key, i, miss_) => {
            if (key!="font") {
                if (i == miss_.length - 2) {
                    this.dl(key, null, function (res) {
                        wx.hideNavigationBarLoading();
                        callback(res);
                    })
                }
                else {
                    this.dl(key);
                }
            }
            else if (key == 'font' && i == miss_.length - 1) {
                wx.hideNavigationBarLoading();
            }
        })
        if (miss.length == 0) {
            wx.hideNavigationBarLoading();
            callback();
        }
    },
    clean() {
        console.log("超出限制，开始清除");
        const pathList = this.all;
        let storage = [];
        this.keys.forEach((key, i, keys) => {
            storage.push(pathList[key])
        })

        wx.getSavedFileList({
            success(res) {
                if (!res.fileList.length) {
                    return;
                }
                for (let i = 0; i < res.fileList.length; i++) {
                    let fp = res.fileList[i].filePath;
                    if (storage.indexOf(fp) == -1) {
                        wx.removeSavedFile({
                            filePath: res.fileList[i].filePath
                        })
                    }
                }
            }
        })
    },
    get all() {
        var temp = new Object();
        this.keys.forEach((key, i, keys) => {
            if (this.check(key)) {
                temp[key] = this.check(key);
            }
            else {
                temp[key] = "cloud://cards-2c53b0.6361-cards-2c53b0-1258076431/mold/" + key + ".png";
            }
        })
        return temp;
    },
    dlFont(resolve = function () { }, reject = function () { }) {
        const that = this;

        wx.getStorage({
            key: "font",
            success(res) {
                resolve(res.data);
            },
            fail(res) {
                that.dl("font", "cloud://cards-2c53b0.6361-cards-2c53b0-1258076431/mold/font/text.ttf", resolve, reject);
            }
        })
    },
    loadFont(callback = function () { }) {
        const that = this;

        this.dlFont(
            function (url) {
                console.log("字体路径加载",url)
                wx.loadFontFace({
                    family: "LiShu",
                    source: 'url("' + url + '")',
                    success() {
                        console.log("字体加载成功")
                        callback();
                    },
                    fail(e) {
                        console.log("字体加载失败",url);
                        const fs = wx.getFileSystemManager();
                        let newPath = url.split(".");
                        newPath.splice(-1, 1);
                        newPath = newPath.join(".") + ".ttf";
                        fs.copyFile({
                            srcPath: url,
                            destPath: newPath,
                            success() {
                                console.log("改名成功");
                                wx.loadFontFace({
                                    family: "LiShu",
                                    source: 'url("' + newPath + '")',
                                    success() {
                                        console.log("字体加载成功")
                                        wx.setStorageSync("font", newPath);
                                        callback();
                                    },
                                    fail() {
                                        console.log("字体加载失败")
                                    }
                                })
                            },
                            fail(e) {
                                console.log("改名失败",e);
                                wx.loadFontFace({
                                    family: "LiShu",
                                    source: 'url("https://xmg520-1257059753.cos.ap-guangzhou.myqcloud.com/text.ttf")',
                                    success() {
                                        console.log("使用备用线路加载字体")
                                        callback()
                                    }
                                });
                            }
                        })
                    }
                })
            },
            function () {
                console.log("字体路径获取失败")
                wx.loadFontFace({
                    family: "LiShu",
                    source: 'url("https://xmg520-1257059753.cos.ap-guangzhou.myqcloud.com/text.ttf")',
                    success() {
                        console.log("使用备用线路加载字体")
                        callback()
                    }
                });
            }
        )
    },
    tempDl(url, callback) {
        const that = this;
        wx.cloud.downloadFile({
            fileID: url,
            success(res) {
                if (res.statusCode === 200) {
                    callback(res.tempFilePath);
                }
                else {
                    console.log(url + "下载失败")
                    that.clean();
                }
            },
            fail() {
                console.log(url + "下载失败")
                that.clean();
            }
        })
    }
}

module.exports.file = file;